<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport( 'joomla.application.component.view' );
jimport('joomla.html.pane');


class JAJobBoardViewJACategories extends JAView
{
    /**
     * Display the view
     */
    function display($tpl = null)
    {
    	$task = JRequest::getVar("task", '');
		switch ($task){
			case 'add':
			case 'edit':				
				JAJobBoardViewJACategories::setLayout("form");
				JAJobBoardViewJACategories::displayForm($tpl);
				break;
			case 'show_import':				
				JAJobBoardViewJACategories::setLayout("show_import");				
				JAJobBoardViewJACategories::displayImportForm($tpl);
				break;			
			default:
				JAJobBoardViewJACategories::displayListItems($tpl);
		}
    }
    
    /**
     * Show import Form
     * */
    function displayImportForm($tpl){
    	
    	parent::display($tpl);
    }
    
    /**
  	* Display List of items
  	*/
  	function displayListItems($tpl){
  		global $mainframe, $option;
  		
        $option_1 = $option.'.jacats';               
		$search				= $mainframe->getUserStateFromRequest( "$option_1.search", 'search', 	'',	'string' );
		$search				= JString::strtolower( $search );
		
        $list = $this->builtTreeCategories($search);  
		$total = $this->get('Total');
		jimport('joomla.html.pagination');
		
		$lists = $this->_getViewLists();		
		$this->_pagination = new JPagination( $total, $lists['limitstart'], $lists['limit'] );		
		$count = ($lists['limit']<count($list))?$lists['limit']:count($list);
		$this->assignRef('lists', $lists);
        $this->assignRef('items', $list);
        $this->assignRef('pagination', $this->_pagination);
        $this->assignRef('count_items',$count);
        $this->assignRef('ordering', $ordering);
        parent::display($tpl);
  	}   
  
  	function builtTreeCategories($search){
  		// get data items
        $model = $this->getModel('jacategories');
        
        if ($search) {
        	$search_rows = $model->getItems(true);
        }
       	
        $items = $model->getItems(); 
                
        $children = array();
		// first pass - collect children
		$list = array();
		if($items){
			foreach ($items as $v )
			{
				$pt = $v->parent_id;			
				$list = @$children[$pt] ? $children[$pt] : array();
				array_push( $list, $v );
				$children[$pt] = $list;			
			}	

			$list = $this->treerecurse(0, '', array(), $children );
			
			if($list){
				foreach ($list as $i => $item) {
					$treename = $item->treename;			
					$treename = JFilterOutput::ampReplace($treename);
					$treename = str_replace('"', '&quot;', $treename);
					if($item->id == 0)
						$list[$i]->treename = $treename;
					else 	
						$list[$i]->treename = $treename;
				}
			}
		}
		
		if ($search) {
			$list1 = array();
			if($search_rows){
				foreach ($search_rows as $srow )
				{
					foreach ($list as $item)
					{
						if ($item->id == $srow->id) {
							$list1[] = $item;
						}
					}
				}
			}
			// Replace full list with found items
			$list = $list1;
		}
		return $list;
  	}
  	/**
  	* Display edit form
  	*/
  	function displayForm($tpl){
  		global $option;
  		
  		$model = $this->getModel('jacategories');
  		 
  	    $item = $this->get('Item');
  	    // toolbar display  	   
		
		$put[] = JHTML::_('select.option',  '1', JText::_( 'Yes' ));
		$put[] = JHTML::_('select.option',  '0', JText::_( 'No' ));
		// If not a new item, trash is not an option
		
		if ( !$item->id) {
			$item->published = 1;
		}
		$published = JHTML::_('select.radiolist',  $put, 'published', '', 'value', 'text', $item->published );		
  	    
  	    // clean item data
		JFilterOutput::objectHTMLSafe( $item, ENT_QUOTES, '' );  	    
		$tree = $this->builtTreeEdit($item);
		
		$data = $item->params;
		$file 	= JPATH_COMPONENT_ADMINISTRATOR.DS.'views'.DS.'jacategories'.DS.'params.xml';
		if(file_exists($file))
			$item->params = new JParameter($data, $file);
		else $params = new JParameter('');
		
		$this->assignRef('item', $item);
  	    $this->assignRef('parent_id', $parentId);
  	    $this->assignRef('published', $published);
  	    $this->assignRef('tree', $tree);
  	    $this->assignRef('option', $option);
  	      	    
  	    $pane = &JPane::getInstance('sliders', array('allowAllClose' => true));
		$this->assignRef('pane', $pane);		
  	    
  	    parent::display();
  	}
  	
  	function &_getViewLists()
	{
		global $mainframe, $option;
		$db		=& JFactory::getDBO();

		$option_1 = $option.'.jacategories';
		
		
  		$lists['limitstart'] 	= $mainframe->getUserStateFromRequest( "$option_1.limitstart", 'limitstart', 	0 );
  		$lists['limit'] 		= $mainframe->getUserStateFromRequest( "$option_1.limit", 'limit', 	20 );
  		$filter_order		= $mainframe->getUserStateFromRequest( "$option_1.filter_order",		'filter_order',		's.ordering',	'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( "$option_1.filter_order_Dir",	'filter_order_Dir',	'ASC',			'word' );
		$filter_state		= $mainframe->getUserStateFromRequest( "$option_1.filter_state",		'filter_state',		'',				'word' );
		$search				= $mainframe->getUserStateFromRequest( "$option_1.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );		

		// state filter
		$lists['state']	= JHTML::_('grid.state',  $filter_state );

		// table ordering
		$lists['order_Dir']	= $filter_order_Dir;
		$lists['order']		= $filter_order;
		
		$lists['option']	= $option;

		// search filter
		$lists['search']= $search;

		return $lists;
	}
  	
  	function builtTreeEdit( &$row, $name='parent_id', $size=10, $options='', $selected='' )
	{
		$db =& JFactory::getDBO();

		// If a not a new item, lets set the menu item id
		if ( $row->id ) {
			$where = ' where id != '.(int) $row->id;
		} else {
			$id = null;
			$where = '';
		}

		// In case the parent was null
		if (!$row->parent_id) {
			$row->parent_id = 0;
		}

		// get a list of the menu items
		// excluding the current menu item and its child elements
		$query = 'SELECT m.id,m.name,IFNULL(m.parent_id,0) parent_id' .
				' FROM #__ja_categories m' .$where.			
				' ORDER BY name';
		$db->setQuery( $query );		
		$treeItems = $db->loadObjectList();
		if ($treeItems) {
			// first pass - collect children
			foreach ($treeItems as $v) {	// iterate through the menu items
				$pt 	= $v->parent_id;		// we use parent as our array index
				// if an array entry for the parent doesn't exist, we create a new array
				$list 	= @$children[$pt] ? $children[$pt] : array();
				
				// we push our item onto the array (either the existing one for the specified parent or the new one
				array_push( $list, $v );
				// We put out updated list into the array
				$children[$pt] = $list;
			}
		}
		
		// second pass - get an indent list of the items
		$list = $this->treerecurse( 0, '', array(), $children, 9999, 0, 0 );

		$treeItems 	= array();
		$treeItems[] 	= JHTML::_('select.option',  '0', '--'.JText::_( 'Select category' ).'--' );
		
		foreach ( $list as $item ) {
			$treeItems[] = JHTML::_('select.option',  $item->id, '&nbsp;&nbsp;&nbsp;'. $item->treename );
		}
		
		if(!$selected) $selected = $row->parent_id;
		$output = JHTML::_('select.genericlist',   $treeItems, $name, 'class="inputbox" size="'.$size.'" style="width:200px"'. $options, 'value', 'text',  $selected);
		return $output;
	}
	/**
	 * Built tree
	 * */
	
	function treerecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 )
	{
		if (@$children[$id] && $level <= $maxlevel)
		{
			foreach ($children[$id] as $v)
			{
				$id = $v->id;

				if ( $type ) {
					$pre 	= '<sup>|_</sup>&nbsp;';
					$spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
				} else {
					$pre 	= '- ';
					$spacer = '&nbsp;&nbsp;';
				}

				if ( $v->parent_id == 0 ) {
					$txt 	= $v->name;
				} else {
					$txt 	= $pre . $v->name;
				}

				$pt = $v->parent_id;
				$list[$id] = $v;
				$list[$id]->treename = "$indent$txt";
				$list[$id]->children = count( @$children[$id] );
				$list = $this->treeRecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
			}
		}
		
		return $list;
	}
	
}
?>